package com.metel.mservice.common.faultcode.message;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;
import java.util.regex.Matcher;

import com.metel.mservice.common.jaxrs.BindErrorFaultCode;
import com.metel.mservice.common.utils.SystemInfo;

/**
 * FaultCode Resource Binder
 * 
 * @author 
 */
public class FaultCodeResource {

	private static ResourceBundle bundle = ResourceBundle.getBundle("FaultMessage");

	private static final String Default_Fault_Message = "Unknown error occurred";

	private static final String ReplaceString = "#argument#";

	private FaultCodeResource() {
		// do nothing..
	}

	/**
	 * Create error message from JAXRSAnnotation
	 * 
	 * @param annotation
	 * @param contentType
	 * @return
	 */
	public static String fromJAXRSAnnotation(BindErrorFaultCode annotation, String contentType) {
		String faultCode = null;

		if (annotation != null) {
			if (contentType != null && contentType.toLowerCase().indexOf("json") >= 0) {
				faultCode = annotation.json();
			} else {
				faultCode = annotation.xml();
			}
		}

		if (faultCode == null) {
			faultCode = "COP-00911";
		}

		String message = FaultCodeResource.getMessage(faultCode);
		return createErrorMessage(faultCode, message);
	}

	static String getMessage(String faultCode) {
		String message = null;

		try {
			message = bundle.getString(faultCode);
		} catch (Exception e) {
			// do nothing..
		}

		if (message == null) {
			message = Default_Fault_Message;
		}

		return message;
	}

	static String getMessage(String key, Object... replaceStr) {
		String message = getMessage(key);

		if (replaceStr != null) {
			// replace arguments
			for (int i = 0; i < replaceStr.length; i++) {
				if (message.indexOf(ReplaceString) < 0) {
					break;
				}

				String replacement = replaceStr[i].toString();
				if (replacement != null) {
					try {
						message = message.replaceFirst(ReplaceString, replacement);
					} catch (Exception e) {
						// try again..
						if(replacement.indexOf('$') >= 0) {
							replacement = Matcher.quoteReplacement(replacement);  
						}
						
						message = message.replaceFirst(ReplaceString, replacement);
					}
					
				}
			}
		}

		if (message == null) {
			message = Default_Fault_Message;
		}

		return message;
	}

	static String createErrorMessage(String faultCode, String message) {
		StringBuilder buff = new StringBuilder();
		
		if ( !faultCode.equals("COP-00911") ) {
			buff.append(getPrefixString());
			buff.append("[");
			buff.append(faultCode);
			buff.append("]");
			buff.append(" ");
			buff.append(message);
		}
		else {
			buff.append("{\"error_code\":\"").append(faultCode)
					.append("\",\"error_msg\":\"").append(message)
					.append("\"}");
		}

		return buff.toString();
	}

	/**
	 * return prefix string for error message
	 * 
	 * @return [ServerAddress] + [CurrentTimeMillis]
	 */
	private static String getPrefixString() {
		StringBuffer buff = new StringBuffer(70);

		Date date = new Date();
		String simpledate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(date);
		buff.append("[");
		buff.append(SystemInfo.publicAddress);
		buff.append("][");
		buff.append(simpledate);
		buff.append("]");

		return buff.toString();
	}
}
